package com.cq.hd.base;

import com.alibaba.fastjson.JSON;
import com.cq.hd.common.annotation.LoginUser;
import com.cq.hd.common.constant.RedisKeyConstant;
import com.cq.hd.common.entity.AppLoginUser;
import com.cq.hd.common.entity.UserInfo;
import com.cq.hd.common.utils.JwtUtil;
import com.cq.hd.common.utils.RedisUtil;
import com.cq.hd.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.validation.constraints.NotNull;

/**
 * @description: 设置App用户信息
 * @author: mYunYu
 * @date: 2021/7/9 10:35
 * @version: v1.0
 */
@Configuration
public class AppLoginUserMethodArgumentResolver implements HandlerMethodArgumentResolver {

    private RedisUtil redisUtil;

    @Autowired
    public void setRedisUtil(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(@NotNull MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        AppLoginUser appLoginUser = new AppLoginUser();
        String token = webRequest.getHeader("Authorization");
        if (StringUtils.isNullOrEmpty(token)) {
            return appLoginUser;
        }
        Long userId = Long.valueOf(JwtUtil.getAudience(token, 0));
        appLoginUser.setUserId(userId);
        String userInfoRedis = redisUtil.get(String.format(RedisKeyConstant.USER_INFO_KEY, userId));
        if (!StringUtils.isNullOrEmpty(userInfoRedis)) {
            UserInfo userInfo = JSON.parseObject(userInfoRedis, UserInfo.class);
            appLoginUser.setUserInfo(userInfo);
        }
        return appLoginUser;
    }
}
